package cn.interestingshop.dao;

import org.apache.commons.dbutils.DbUtils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @Description mysql数据源工具类
 **/
public class DataSourceUtil {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    static {
        init();
    }

    public static void init() {
        Properties params = new Properties();
        String configFile = "database.properties";
        InputStream is = DataSourceUtil.class.getClassLoader().getResourceAsStream(configFile);
        try {
            params.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = params.getProperty("driver");
        url = params.getProperty("url");
        user = params.getProperty("username");
        password = params.getProperty("password");
    }

    //获取连接
    public static Connection openConnection() {
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return connection;
    }

    //关闭连接
    public static void closeConnection(Connection connection) {
        try {
            if (connection != null)
              //  connection.close();
                DbUtils.close(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //释放资源
    public boolean closeResource(Statement pstm) {
        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    public boolean closeResource(ResultSet reSet) {
        if (reSet != null) {
            try {
                reSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }
}
